<script setup>
import { useFloating, autoUpdate, offset, flip, shift } from "@floating-ui/vue";
import menu from './_menu';
import _ from "lodash";
import { ref, defineProps } from 'vue';
import './dropdown.scss'; // 引入公共样式

const props = defineProps({
    icon: {
        type: String,
        default: ''
    },
    group: {
        type: Boolean,
        default: false
    },
    devided: {
        type: Boolean,
        default: false
    },
    label: {
        type: String,
        default: ''
    },
    events: {
        type: Object,
        default: () => ({})
    }
});

const current = ref(null);
const floating = ref(null);
const open = ref(false);

const { floatingStyles } = useFloating(current, floating, {
    placement: "right-center", // 默认位置
    middleware: [
        offset(0), // 浮层和目标元素之间的间距
        flip({
            fallbackPlacements: ["righ-center", "left-center"], // 自动翻转的备选位置
            padding: 10, // 浮层和视口边界之间的最小间距
        }),
        shift({
            padding: 10, // 浮层和视口边界之间的最小间距
        }),
    ],
    whileElementsMounted: autoUpdate, // 自动更新浮层位置
});

const switchOpenFn = () => {
    menu.switchOpen(current.value, open);
};
const setCurrent = (el) => {
    current.value = el;
};
</script>

<template>
    <div class="x-dropdown-item w-100 d-flex" :ref="setCurrent" :class="{ 'x-dropdown-group': group, devided: devided }"
        @click.stop="switchOpenFn" v-on="events">
        <div v-if="icon" class="x-dropdown-item-icon">
            <i :class="icon"></i>
        </div>
        <div class="x-dropdown-item-label d-inline-blck" v-if="label" :class="group?'text-start':'text-end'">
            {{ label }}
        </div>
        <div class="x-dropdown-item-suffix text-end">
            <i class="iconfont te-i-jiantou_liebiaoxiangyou"></i>
        </div>
        <div class="x-dropdown shadow-lg rounded-3" ref="floating" :style="floatingStyles" v-if="open">
            <span class="x-dropdown-body w-100">
                <slot></slot>
            </span>
        </div>
        <hr v-if="group" class="x-dropdown-group" />
    </div>
</template>